﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;

namespace System.Controls.Base
{
  internal class DeferSelection
  {
    private readonly DependencyObject fOwner;

    private int fSelectedIndex;

    private object fSelectedItem;

    private string fSelectedValuePath;

    private DeferredType fType;

    public DeferSelection( DependencyObject owner )
    {
      fOwner = owner;
    }

    public bool HasDeferredSelection
    {
      get { return fType != DeferredType.None; }
    }

    public void SetDeferred( object value, DeferredType type )
    {
      var selection = type & DeferredType.Selection;
      fType |= type;

      if ( selection != DeferredType.None )
      {
        fSelectedIndex = -1;
        fSelectedItem = null;
      }

      switch ( type )
      {
      case DeferredType.Index:
        fSelectedIndex = (int)value;
        break;

      case DeferredType.Item:
      case DeferredType.Value:
        fSelectedItem = value;
        break;

      default:
        if ( type.HasFlag( DeferredType.ValuePath ) && value != null )
          fSelectedValuePath = value.ToString();

        break;
      }
    }

    public void UpdateDeferredSelection()
    {
      if ( fType.HasFlag( DeferredType.ValuePath ) ) {}

      var selection = fType & DeferredType.Selection;

      switch ( selection )
      {
      case DeferredType.Index:
        Selection.SetSelectedIndex( fOwner, fSelectedIndex );
        break;

      case DeferredType.Item:
        Selection.SetSelectedItem( fOwner, fSelectedItem );
        break;

      case DeferredType.Value:
        Selection.SetSelectedValue( fOwner, fSelectedItem );
        break;
      }

      fType = DeferredType.None;
    }
  }
}
